<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\adminapi\controller\user;

use app\adminapi\controller\Base;
use app\common\model\User as UserModel;
use think\facade\Db;

class Member extends Base
{
    /**
     * Member list
     */
    public function list()
    {
        $where = $this->request->params([
            ['email', ''],
            ['nickname', ''],
            ['status', ''],
            ['is_freeze', '']
        ]);

        $list = UserModel::withSearch(array_keys($where[1]), $where[1])
            ->order('id desc')
            ->paginate($this->limit)->each(
                function ($item) {
                    // $item->avatar = $item->avatar;
                    $item->setAttr('avatar', $item->avatar);
                }
            );

        $this->success('', [
            'list'  => $list->items(),
            'total' => $list->total(),
        ]);
    }

    /**
     * Member details
     */
    public function detail()
    {
        $id = inputs('id/d', 0);

        if (!$id) {
            $this->error(trans('parameter_error'));
        }

        $user = UserModel::find($id);

        if (!$user) {
            $this->error(trans('member_not_exists'));
        }

        $this->success('', $user);
    }

    /**
     * Edit member
     */
    public function edit()
    {
        $id = inputs('id/d', 0);

        if (!$id) {
            $this->error(trans('parameter_error'));
        }

        $user = UserModel::find($id);

        if (!$user) {
            $this->error(trans('member_not_exists'));
        }

        $post = [
            'nickname'  => inputs('nickname/s', ''),
            'avatar'    => inputs('avatar/s', ''),
            'status'    => inputs('status/d', 1),
            'is_freeze' => inputs('is_freeze/d', 0),
        ];

        // If email is provided, validate if email is already in use
        $email = inputs('email/s', '');
        if ($email && $email != $user->email) {
            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $this->error(trans('email_format_invalid'));
            }

            $existUser = UserModel::where('email', $email)
                ->where('id', '<>', $id)
                ->find();

            if ($existUser) {
                $this->error(trans('email_already_used'));
            }

            $post['email'] = $email;
        }

        // If password is provided, update password
        $password = inputs('password/s', '');
        if ($password) {
            $post['password'] = password_hash($password, PASSWORD_DEFAULT);
        }

        $user->save($post);

        $this->success();
    }

    /**
     * Delete member
     */
    public function del()
    {
        $id = inputs('id/d', 0);

        if (!$id) {
            $this->error(trans('parameter_error'));
        }

        $user = UserModel::find($id);

        if (!$user) {
            $this->error(trans('member_not_exists'));
        }

        // Start transaction
        Db::startTrans();
        try {
            // Delete member related data
            // Here you can add logic to delete other associated data of the member

            // Delete member
            $user->delete();

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success();

    }

    /**
     * Update member status
     */
    public function status()
    {
        $id = inputs('id/d', 0);

        if (!$id) {
            $this->error(trans('parameter_error'));
        }

        $user = UserModel::find($id);

        if (!$user) {
            $this->error(trans('member_not_exists'));
        }

        $user->status = $user->status ? 0 : 1;
        $user->save();

        $this->success();
    }

    /**
     * Update member freeze status
     */
    public function freeze()
    {
        $id = inputs('id/d', 0);

        if (!$id) {
            $this->error(trans('parameter_error'));
        }

        $user = UserModel::find($id);

        if (!$user) {
            $this->error(trans('member_not_exists'));
        }

        $user->is_freeze = $user->is_freeze ? 0 : 1;
        $user->save();

        $this->success();
    }

    /**
     * Reset password
     */
    public function resetPassword()
    {
        $id = inputs('id/d', 0);

        if (!$id) {
            $this->error(trans('parameter_error'));
        }

        $user = UserModel::find($id);

        if (!$user) {
            $this->error(trans('member_not_exists'));
        }

        $password = inputs('password/s', '');

        if (!$password) {
            $this->error(trans('please_enter_new_password'));
        }

        $user->password = password_hash($password, PASSWORD_DEFAULT);
        $user->save();

        $this->success();
    }
}